<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="文章标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入文章标题"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="分类" prop="category">
        <el-select v-model="queryParams.category" placeholder="请选择分类" clearable>
          <el-option label="基础入门" value="基础入门" />
          <el-option label="钓法技巧" value="钓法技巧" />
          <el-option label="饵料配方" value="饵料配方" />
          <el-option label="装备选择" value="装备选择" />
          <el-option label="钓点选择" value="钓点选择" />
        </el-select>
      </el-form-item>
      <el-form-item label="难度" prop="difficulty">
        <el-select v-model="queryParams.difficulty" placeholder="请选择难度" clearable>
          <el-option label="初级" value="初级" />
          <el-option label="中级" value="中级" />
          <el-option label="高级" value="高级" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="文章状态" clearable>
          <el-option label="启用" value="1" />
          <el-option label="禁用" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['fishing:technique:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['fishing:technique:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['fishing:technique:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['fishing:technique:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="techniqueList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="文章ID" align="center" prop="id" width="80" />
      <el-table-column label="封面图片" align="center" prop="imageUrl" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.imageUrl" :width="50" :height="50" v-if="scope.row.imageUrl"/>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="文章标题" align="center" prop="title" :show-overflow-tooltip="true" />
      <el-table-column label="分类" align="center" prop="category" width="100">
        <template #default="scope">
          <dict-tag :options="categoryOptions" :value="scope.row.category"/>
        </template>
      </el-table-column>
      <el-table-column label="难度" align="center" prop="difficulty" width="80">
        <template #default="scope">
          <el-tag :type="getDifficultyTagType(scope.row.difficulty)">{{ scope.row.difficulty }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="作者" align="center" prop="author" width="100" />
      <el-table-column label="阅读量" align="center" prop="readCount" width="80" />
      <el-table-column label="点赞数" align="center" prop="likeCount" width="80" />
      <el-table-column label="收藏数" align="center" prop="favoriteCount" width="80" />
      <el-table-column label="评论数" align="center" prop="commentCount" width="80" />
      <el-table-column label="状态" align="center" prop="status" width="80">
        <template #default="scope">
          <el-tag :type="scope.row.status === '1' ? 'success' : 'danger'">
            {{ scope.row.status === '1' ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleView(scope.row)">查看</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['fishing:technique:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['fishing:technique:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改钓技文章对话框 -->
    <el-dialog :title="title" v-model="open" width="900px" append-to-body>
      <el-form ref="techniqueRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="文章标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入文章标题" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="副标题" prop="subtitle">
              <el-input v-model="form.subtitle" placeholder="请输入文章副标题" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="分类" prop="category">
              <el-select v-model="form.category" placeholder="请选择分类">
                <el-option label="基础入门" value="基础入门" />
                <el-option label="钓法技巧" value="钓法技巧" />
                <el-option label="饵料配方" value="饵料配方" />
                <el-option label="装备选择" value="装备选择" />
                <el-option label="钓点选择" value="钓点选择" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="难度" prop="difficulty">
              <el-select v-model="form.difficulty" placeholder="请选择难度">
                <el-option label="初级" value="初级" />
                <el-option label="中级" value="中级" />
                <el-option label="高级" value="高级" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="作者" prop="author">
              <el-input v-model="form.author" placeholder="请输入作者" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预计阅读时间" prop="estimatedReadTime">
              <el-input-number v-model="form.estimatedReadTime" :min="1" :max="999" placeholder="分钟" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="标签" prop="tags">
          <el-input v-model="form.tags" placeholder="请输入标签，多个标签用逗号分隔" />
        </el-form-item>
        <el-form-item label="封面图片" prop="imageUrl">
          <image-upload v-model="form.imageUrl"/>
        </el-form-item>
        <el-form-item label="文章内容" prop="content">
          <wang-editor v-model="form.content" :min-height="300"/>
        </el-form-item>
        <el-form-item label="排序" prop="sortOrder">
          <el-input-number v-model="form.sortOrder" controls-position="right" :min="0" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="1">启用</el-radio>
            <el-radio label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看文章详情对话框 -->
    <el-dialog title="文章详情" v-model="viewOpen" width="1000px" append-to-body>
      <div v-if="viewData">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="文章标题">{{ viewData.title }}</el-descriptions-item>
          <el-descriptions-item label="副标题">{{ viewData.subtitle || '-' }}</el-descriptions-item>
          <el-descriptions-item label="分类">{{ viewData.category }}</el-descriptions-item>
          <el-descriptions-item label="难度">{{ viewData.difficulty }}</el-descriptions-item>
          <el-descriptions-item label="作者">{{ viewData.author }}</el-descriptions-item>
          <el-descriptions-item label="预计阅读时间">{{ viewData.estimatedReadTime }}分钟</el-descriptions-item>
          <el-descriptions-item label="阅读量">{{ viewData.readCount }}</el-descriptions-item>
          <el-descriptions-item label="点赞数">{{ viewData.likeCount }}</el-descriptions-item>
          <el-descriptions-item label="收藏数">{{ viewData.favoriteCount }}</el-descriptions-item>
          <el-descriptions-item label="评论数">{{ viewData.commentCount }}</el-descriptions-item>
          <el-descriptions-item label="标签">{{ viewData.tags || '-' }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="viewData.status === '1' ? 'success' : 'danger'">
              {{ viewData.status === '1' ? '启用' : '禁用' }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
        <div style="margin-top: 20px;" v-if="viewData.imageUrl">
          <h4>封面图片：</h4>
          <el-image :src="viewData.imageUrl" style="width: 200px; height: 150px;" fit="cover" />
        </div>
        <div style="margin-top: 20px;">
          <h4>文章内容：</h4>
          <div v-html="viewData.content" style="border: 1px solid #ddd; padding: 15px; border-radius: 4px; max-height: 400px; overflow-y: auto;"></div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="Technique">
import { listTechnique, getTechnique, delTechnique, addTechnique, updateTechnique, exportTechnique } from "@/api/fishing/technique";
import WangEditor from '@/components/WangEditor/index.vue';

const { proxy } = getCurrentInstance();

const techniqueList = ref([]);
const open = ref(false);
const viewOpen = ref(false);
const viewData = ref(null);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    title: null,
    category: null,
    difficulty: null,
    status: null
  },
  rules: {
    title: [
      { required: true, message: "文章标题不能为空", trigger: "blur" }
    ],
    category: [
      { required: true, message: "分类不能为空", trigger: "change" }
    ],
    difficulty: [
      { required: true, message: "难度不能为空", trigger: "change" }
    ],
    content: [
      { required: true, message: "文章内容不能为空", trigger: "blur" }
    ]
  }
});

const categoryOptions = ref([
  { label: "基础入门", value: "基础入门" },
  { label: "钓法技巧", value: "钓法技巧" },
  { label: "饵料配方", value: "饵料配方" },
  { label: "装备选择", value: "装备选择" },
  { label: "钓点选择", value: "钓点选择" }
]);

const { queryParams, form, rules } = toRefs(data);

/** 查询钓技文章列表 */
function getList() {
  loading.value = true;
  listTechnique(queryParams.value).then(response => {
    techniqueList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    title: null,
    subtitle: null,
    content: null,
    imageUrl: null,
    category: null,
    difficulty: null,
    tags: null,
    author: "钓技专家",
    estimatedReadTime: 5,
    sortOrder: 0,
    status: "1",
    remark: null
  };
  proxy.resetForm("techniqueRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加钓技文章";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const id = row.id || ids.value;
  getTechnique(id).then(response => {
    form.value = response.data;
    // 清除日期字段，避免提交时格式问题
    delete form.value.createTime;
    delete form.value.updateTime;
    open.value = true;
    title.value = "修改钓技文章";
  });
}

/** 查看按钮操作 */
function handleView(row) {
  getTechnique(row.id).then(response => {
    viewData.value = response.data;
    viewOpen.value = true;
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["techniqueRef"].validate(valid => {
    if (valid) {
      console.log('原始form.value.content:', form.value.content);
      
      // 创建提交数据的副本，排除日期字段
      const submitData = {
        id: form.value.id,
        title: form.value.title,
        subtitle: form.value.subtitle,
        content: encodeURIComponent(form.value.content), // axios会自动处理JSON转义
        imageUrl: form.value.imageUrl,
        category: form.value.category,
        difficulty: form.value.difficulty,
        tags: form.value.tags,
        author: form.value.author,
        estimatedReadTime: form.value.estimatedReadTime,
        sortOrder: form.value.sortOrder,
        status: form.value.status,
        remark: form.value.remark
      };
      
      console.log('submitData.content:', submitData.content);
      console.log('提交数据:', JSON.stringify(submitData, null, 2));
      
      if (form.value.id != null) {
        updateTechnique(submitData).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        }).catch(error => {
          console.error('更新失败:', error);
          proxy.$modal.msgError("更新失败: " + (error.message || error));
        });
      } else {
        addTechnique(submitData).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        }).catch(error => {
          console.error('新增失败:', error);
          proxy.$modal.msgError("新增失败: " + (error.message || error));
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const techniqueIds = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除钓技文章编号为"' + techniqueIds + '"的数据项？').then(function() {
    return delTechnique(techniqueIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}


/** 导出按钮操作 */
function handleExport() {
  proxy.download('pond/app/fishing/technique/export', {
    ...queryParams.value
  }, `technique_${new Date().getTime()}.xlsx`)
}

/** 获取难度标签类型 */
function getDifficultyTagType(difficulty) {
  switch(difficulty) {
    case '初级': return 'success';
    case '中级': return 'warning';
    case '高级': return 'danger';
    default: return '';
  }
}

getList();
</script>